<template>
  <div class="chat-window">
    <div class="chat-tabs">
      <button 
        :class="{ active: activeTab === 'global' }"
        @click="activeTab = 'global'"
      >
        全局聊天
      </button>
      <button 
        :class="{ active: activeTab === 'private' }"
        @click="activeTab = 'private'"
      >
        私聊
        <span v-if="unreadCount" class="unread-badge">
          {{ unreadCount }}
        </span>
      </button>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <template v-if="activeTab === 'global'">
        <div 
          v-for="message in globalMessages" 
          :key="message.id"
          class="message"
          :class="{ 
            'own-message': message.from.id === currentUserId,
            [message.type]: true
          }"
        >
          <div class="message-header">
            <img :src="message.from.avatar" class="avatar" />
            <span class="username">{{ message.from.username }}</span>
            <span class="time">{{ formatTime(message.timestamp) }}</span>
          </div>
          <div class="message-content">
            <template v-if="message.type === 'text'">
              {{ message.content }}
            </template>
            <template v-else-if="message.type === 'move'">
              <div class="move-notation">{{ message.content }}</div>
            </template>
            <template v-else-if="message.type === 'emoji'">
              <div class="emoji">{{ message.content }}</div>
            </template>
            <template v-else-if="message.type === 'system'">
              <div class="system-message">{{ message.content }}</div>
            </template>
          </div>
        </div>
      </template>

      <template v-else>
        <div class="private-chats">
          <div 
            v-for="chat in privateChats" 
            :key="chat.userId"
            class="chat-item"
            :class="{ active: selectedChat === chat.userId }"
            @click="selectChat(chat.userId)"
          >
            <img :src="chat.avatar" class="avatar" />
            <div class="chat-info">
              <div class="username">{{ chat.username }}</div>
              <div class="last-message">{{ chat.lastMessage }}</div>
            </div>
            <div class="chat-meta">
              <div class="time">{{ formatTime(chat.lastTime) }}</div>
              <div 
                v-if="chat.unreadCount" 
                class="unread-count"
              >
                {{ chat.unreadCount }}
              </div>
            </div>
          </div>
        </div>

        <div v-if="selectedChat" class="private-messages">
          <div 
            v-for="message in getPrivateChat(selectedChat)"
            :key="message.id"
            class="message"
            :class="{ 
              'own-message': message.from.id === currentUserId,
              [message.type]: true
            }"
          >
            <div class="message-content">
              {{ message.content }}
            </div>
            <div class="message-time">
              {{ formatTime(message.timestamp) }}
            </div>
          </div>
        </div>
      </template>
    </div>

    <div class="chat-input">
      <div class="input-toolbar">
        <button @click="showEmoji = !showEmoji">😊</button>
        <button @click="$emit('share-position')">分享局面</button>
      </div>
      
      <div v-if="showEmoji" class="emoji-picker">
        <div 
          v-for="emoji in emojis" 
          :key="emoji"
          class="emoji"
          @click="insertEmoji(emoji)"
        >
          {{ emoji }}
        </div>
      </div>

      <div class="input-area">
        <textarea 
          v-model="messageInput"
          @keydown.enter.prevent="sendMessage"
          placeholder="输入消息..."
        ></textarea>
        <button 
          @click="sendMessage"
          :disabled="!messageInput.trim()"
        >
          发送
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { useChatSystem } from '../composables/useChatSystem'
import type { UserProfile } from '../types/social'

const props = defineProps<{
  currentUserId: string
}>()

const emit = defineEmits<{
  (e: 'share-position'): void
}>()

const {
  globalMessages,
  privateMessages,
  sendMessage: sendChatMessage,
  getPrivateChat,
  loadMessages,
  loadGlobalMessages
} = useChatSystem()

const activeTab = ref<'global' | 'private'>('global')
const selectedChat = ref<string | null>(null)
const messageInput = ref('')
const showEmoji = ref(false)
const messagesContainer = ref<HTMLElement | null>(null)

const emojis = ['😊', '😂', '🤔', '👍', '❤️', '😎', '🎮', '♟️']

// 修改消息类型定义
interface ChatMessage {
  id: string
  from: {
    id: string
    username: string
    avatar?: string
    rating: number
    title?: string
    country?: string
    joinDate: Date
    lastActive: Date
    status: 'playing' | 'online' | 'away'
  }
  to: {
    id: string
    username: string
    avatar?: string
  } | null
  content: string
  type: 'text' | 'move' | 'emoji' | 'system'
  timestamp: Date
  isRead: boolean  // 使用 isRead 而不是 read
}

const privateChats = computed(() => {
  const chats = new Map<string, {
    userId: string
    username: string
    avatar: string
    lastMessage: string
    lastTime: Date
    unreadCount: number
  }>()

  ;(privateMessages.value as ChatMessage[]).forEach((message) => {
    const otherUser = message.from.id === props.currentUserId ? message.to! : message.from
    const chat = chats.get(otherUser.id) || {
      userId: otherUser.id,
      username: otherUser.username,
      avatar: otherUser.avatar || '/default-avatar.png',
      lastMessage: '',
      lastTime: new Date(0),
      unreadCount: 0
    }

    if (message.timestamp > chat.lastTime) {
      chat.lastMessage = message.content
      chat.lastTime = message.timestamp
    }

    if (message.from.id !== props.currentUserId && !message.isRead) {
      chat.unreadCount++
    }

    chats.set(otherUser.id, chat)
  })

  return Array.from(chats.values())
})

const unreadCount = computed(() => 
  privateChats.value.reduce((sum, chat) => sum + chat.unreadCount, 0)
)

const selectChat = (userId: string) => {
  selectedChat.value = userId
}

const sendMessage = async () => {
  if (!messageInput.value.trim()) return

  const success = await sendChatMessage(
    messageInput.value,
    selectedChat.value ? { id: selectedChat.value } as UserProfile : null
  )

  if (success) {
    messageInput.value = ''
    await nextTick()
    scrollToBottom()
  }
}

const insertEmoji = (emoji: string) => {
  messageInput.value += emoji
  showEmoji.value = false
}

const formatTime = (date: Date) => {
  const now = new Date()
  const diff = now.getTime() - new Date(date).getTime()
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  
  return new Date(date).toLocaleString()
}

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

onMounted(async () => {
  await Promise.all([
    loadMessages(props.currentUserId),
    loadGlobalMessages()
  ])
  scrollToBottom()
})
</script>

<style scoped>
.chat-window {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.chat-tabs {
  display: flex;
  border-bottom: 1px solid #eee;
}

.chat-tabs button {
  flex: 1;
  padding: 10px;
  border: none;
  background: none;
  cursor: pointer;
  position: relative;
}

.chat-tabs button.active {
  border-bottom: 2px solid #4CAF50;
  color: #4CAF50;
}

.unread-badge {
  position: absolute;
  top: 5px;
  right: 5px;
  background: #f44336;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 12px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.message {
  margin-bottom: 10px;
  max-width: 80%;
}

.own-message {
  margin-left: auto;
  text-align: right;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 5px;
}

.avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
}

.username {
  font-weight: bold;
}

.time {
  font-size: 12px;
  color: #666;
}

.message-content {
  background: #f1f0f0;
  padding: 8px 12px;
  border-radius: 8px;
}

.own-message .message-content {
  background: #e3f2fd;
}

.move-notation {
  font-family: monospace;
  color: #2196F3;
}

.emoji {
  font-size: 24px;
}

.system-message {
  color: #666;
  font-style: italic;
}

.private-chats {
  border-right: 1px solid #eee;
}

.chat-item {
  display: flex;
  padding: 10px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.chat-item:hover {
  background: #f5f5f5;
}

.chat-item.active {
  background: #e3f2fd;
}

.chat-info {
  flex: 1;
  margin: 0 10px;
}

.last-message {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-meta {
  text-align: right;
}

.unread-count {
  background: #f44336;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 12px;
  display: inline-block;
}

.chat-input {
  border-top: 1px solid #eee;
  padding: 10px;
}

.input-toolbar {
  display: flex;
  gap: 5px;
  margin-bottom: 5px;
}

.input-toolbar button {
  padding: 5px 10px;
  border: none;
  background: none;
  cursor: pointer;
}

.emoji-picker {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 5px;
  padding: 5px;
  background: white;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 5px;
}

.emoji-picker .emoji {
  cursor: pointer;
  text-align: center;
  padding: 5px;
  border-radius: 4px;
}

.emoji-picker .emoji:hover {
  background: #f5f5f5;
}

.input-area {
  display: flex;
  gap: 10px;
}

.input-area textarea {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: none;
  height: 60px;
}

.input-area button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background-color: #4CAF50;
  color: white;
  cursor: pointer;
}

.input-area button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style> 